package com.example.vuandroidadsdk.net;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.vuandroidadsdk.R;
import com.example.vuandroidadsdk.okhttp.CommonOkHttpClient;
import com.example.vuandroidadsdk.okhttp.listener.DisposeDataHandle;
import com.example.vuandroidadsdk.okhttp.listener.DisposeDownloadListener;
import com.example.vuandroidadsdk.okhttp.request.CommonRequest;

import java.io.File;

public class DownloadUtils {

    public void downloadApp(final Context context, String url, final OnFileGetListener listener){
        final String path = Environment.getExternalStorageDirectory()+"/HTManager";
        String name = url.substring(url.lastIndexOf("/"),url.length());
        final String filePath = path+ File.separator+name;
        Log.d("fileDowanPath",path);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        final View view = LayoutInflater.from(context).inflate(R.layout.dialog_download,null);
        final ProgressBar bar = view.findViewById(R.id.progressBar);



        CommonOkHttpClient.downloadFile(CommonRequest.createGetRequest(url,null),new DisposeDataHandle(new DisposeDownloadListener() {
            @Override
            public void onProgress(int progrss) {
                dialog.show();
                dialog.setContentView(view);
                bar.setProgress(progrss);
            }

            @Override
            public void onSuccess(Object responseObj) {
                dialog.dismiss();
                File file = new File(filePath);
               listener.onFileGer(file);
            }

            @Override
            public void onFailure(Object reasonObj) {
                Toast.makeText(context,"下载失败",Toast.LENGTH_SHORT).show();
            }
        },filePath));
    }

    public interface OnFileGetListener{
        void onFileGer(File file);
    }
}
